package com.lz.service.smsmail.filter;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.HandlerMapping;

import com.google.gson.Gson;
import com.lz.service.smsmail.common.RequestContext;

/**
 * 日志记录切面，切在control
 * @author likejian
 */
@Aspect
@Component
public class RequestLogAspect {

    private static Logger LOGGER = LoggerFactory.getLogger(RequestLogAspect.class);
    private static Gson GSON = new Gson();

    @Pointcut("execution(public * com.lz.service.smsmail.control.*.*(..))")
    public void requestLog() {}

    @Before("requestLog()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String method = request.getMethod();
        String requestParams = "";
        if ("POST".equals(method)) {
            Object[] paramsArray = joinPoint.getArgs();
            requestParams = GSON.toJson(paramsArray);
        } else {
            Map<?, ?> paramsMap = (Map<?, ?>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
            requestParams = paramsMap.toString();
        }
        RequestContext requestContext = RequestContext.get();
        LOGGER.info("uri={} method={} params={} start", requestContext.getUri(), method, requestParams);
    }

    @AfterReturning(returning = "result", pointcut = "requestLog()")
    public void doAfterReturning(Object result) {
        try {
        	String responseConent = GSON.toJson(result);
        	RequestContext.end(responseConent);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("doAfterReturning " + ExceptionUtils.getFullStackTrace(e));
        }
    }


}